import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:何人亮
 * Date:2024-12-06
 * 21:56
 */
 class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        Map<ListNode,Integer> map=new HashMap<>();

        if(hasCycle(pHead)){
            ListNode cur=pHead;
            while(true){
                if(!map.containsKey(cur)){
                    map.put(cur,1);
                }else {
                    map.put(cur,map.get(cur)+1);
                }
                for (Map.Entry<ListNode,Integer> entry:map.entrySet()) {
                    if(entry.getValue()==2){
                        return entry.getKey();
                    }
                }
            }
        }else{
            return null;
        }
    }
    public boolean hasCycle(ListNode head) {

        ListNode slow=head;
        ListNode fast=head;
        boolean b=false;
        while(fast!=null&&fast.next!=null){

            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast){
                b=true;
                break;
            }
        }
        return b;
    }
}
